package com.jzo2o.customer.controller.open;

import cn.hutool.core.util.ObjectUtil;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.api.publics.dto.response.BooleanResDTO;
import com.jzo2o.common.constants.ErrorInfo;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.Result;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.IServeProviderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/open/serve-provider")
@Api(tags = "白名单接口 - 机构服务提供相关接口")
public class ServeProviderController {

    @Resource
    private IServeProviderService serveProviderService;

    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/institution/register")
    @ApiOperation("机构人员注册接口")
    public Result<Void> register(@RequestBody InstitutionRegisterReqDTO dto) {
        if (ObjectUtil.isNull(dto) || ObjectUtil.isNull(dto.getPassword()) || ObjectUtil.isNull(dto.getPhone())
                || ObjectUtil.isNull(dto.getVerifyCode())) {
            throw new BadRequestException(ErrorInfo.Msg.REQUEST_PARAM_ILLEGAL);
        }

        BooleanResDTO verify = smsCodeApi.verify(dto.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER, dto.getVerifyCode());
        if (!ObjectUtil.isNull(verify) && verify.getIsSuccess()) {
            String password = bCryptPasswordEncoder.encode(dto.getPassword());
            serveProviderService.add(dto.getPhone(), UserType.INSTITUTION, password);
            return Result.ok();
        } else {
            throw new ForbiddenOperationException(ErrorInfo.Msg.PROCESS_FAILD);
        }
    }
}